/***************************************************************************
	This file has functions which do node operations for astar.c
	
	Copyright (C) 2013 Aditya Nag Matsa 
    
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
****************************************************************************/

#include "astar.h"

/************************************************	
	Counts the number of nodes in a list
*************************************************/
int nodeCount (Node *node)
{
	if (node == NULL || node->location == NULL)
		return 0;
	else
		return (1 + nodeCount (node->next));
}


/*************************************************	
	Removes a node from a list
**************************************************/
Node * nodeDelete (Point *point, Node *node)
{
	if ( node == NULL )
		return NULL;
	if ( equalElements(node->location, point) )
	{
		Node* temp = node->next;
		free (node);
		return temp;
	}
	node->next = nodeDelete ( point, node->next );
	return node;
}


/*************************************************************
	Appends a node to a list
**************************************************************/
Node * nodeAppend (Point *point, Node *node)
{
	// At the end point of a list or at the start of a freshly deallocated list
	if (node == NULL)
	{
		node = (Node *) malloc (sizeof(Node));
		node->location = point;
		node->next = NULL;
		return node;
	}
	
	// At the start	a freshly allocated list
	if (node != NULL && node->location == NULL)
	{
		node->location = point;
		node->next = NULL;
		return node;
	}
	node->next = nodeAppend ( point, node->next );
	return node;
}

/**********************************************************
	Searches for a node in a list
***********************************************************/
int nodeSearch (Point *point, Node *node)
{
	while (node != NULL)
	{
		if ( equalElements( point, node->location ) )
			return 1;
		node = node->next;
	}
	return 0;
}

/************************************************************
	Searches for the node with the least f score
*************************************************************/
Point * priority (Node *node)
{
	if (node == NULL)
		return NULL;
	
	Point *currentmin = node->location;
	while (node != NULL)
	{
		if (node->location->f < currentmin->f)
			currentmin = node->location;
		node = node->next;
	}
	return currentmin;
}
